package cc.magicjson.synthesis.decorator;



import cc.magicjson.synthesis.model.Order;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 组合折扣装饰器，可以组合多个装饰器一起使用
 * 实现组合模式，将多个不同类型的折扣组合在一起
 */
public class CompositeDiscountDecorator extends OrderDiscountDecorator {
    private final List<OrderDiscountDecorator> decorators = new ArrayList<>();

    public CompositeDiscountDecorator(Order order) {
        super(order);
    }

    /**
     * 添加折扣装饰器
     * @param decorator 要添加的装饰器
     * @return 当前组合装饰器，便于链式调用
     */
    public CompositeDiscountDecorator addDecorator(OrderDiscountDecorator decorator) {
        decorators.add(decorator);
        return this;
    }

    @Override
    public Order applyDiscount() {
        // 逐个应用各个装饰器
        for (OrderDiscountDecorator decorator : decorators) {
            decorator.applyDiscount();
        }
        return order;
    }

    @Override
    public String getDiscountDescription() {
        StringBuilder builder = new StringBuilder("折扣明细：\n");

        for (OrderDiscountDecorator decorator : decorators) {
            String description = decorator.getDiscountDescription();
            if (!description.startsWith("未使用")) {
                builder.append("- ").append(description).append("\n");
            }
        }

        return builder.toString();
    }

    @Override
    public BigDecimal getDiscountAmount() {
        return decorators.stream()
                .map(OrderDiscountDecorator::getDiscountAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
}
